var express = require('express');
var router = express.Router();

//载入lodash包
const _ = require('lodash')
//载入自动验证表单数据的模块
const expressJoi = require('@escook/express-joi')
//载入验证模块
const {
    cate_add_schema
} = require('../schema/cate')

//载入模型
const CateModel = require('../models')['Cate']
const {
    Op
} = require("sequelize");

//分类添加表单
router.get('/cates/create', (req, res) => {
    res.render('cate/cate_add.html')
})

//分类添加入库
router.post('/cates', expressJoi(cate_add_schema), async (req, res) => {
    try {
        const cate = await CateModel.findAll({
            where: {
                cate_name: req.body.cate_name
            }
        })
        if (cate.length > 0) {
            return res.cc(400, '分类名称重复')
        }
        const result = await CateModel.create(req.body)
        res.cc(201, '添加成功', result)
    } catch (e) {
        res.cc(400, e.message)
    }
})

//分类列表展示
router.get('/cates', (req, res) => {
    res.render('cate/cate_list.html')
})

//获取分类数据
router.get('/cates/getCateList', async (req, res) => {
    const {
        rows: data,
        count
    } = await CateModel.findAndCountAll()
    res.json({
        code: 0,
        msg: '',
        count,
        data
    })
})

//根据id删除数据
router.delete('/cates/:id', async (req, res) => {
    //接收id
    let id = parseInt(req.params.id);
    try {
        const num = await CateModel.destroy({
            where: {
                id
            }
        })
        if (num) {
            res.cc(200, '删除成功')
        } else {
            res.cc(400, '数据不存在')
        }
    } catch (e) {
        res.cc(400, e.message)
    }
})

//根据id查询出该条数据，渲染在修改表单中
router.get('/cates/:id/edit', async (req, res) => {
    let id = parseInt(req.params.id);
    const cate = await CateModel.findByPk(id);
    if (cate) {
        res.render('cate/cate_edit.html', {
            cate
        })
    }
})

//进行数据库的修改
router.put('/cates/:id', expressJoi(cate_add_schema), async (req, res) => {
    try{
         let id = parseInt(req.params.id);
         //唯一性验证(有可能不修改分类名称)
         const data = await CateModel.findAll({
             where: {
                 [Op.and]: {
                     cate_name: req.body.cate_name,
                     id: {
                         [Op.not]: id
                     }
                 }
             }
         })
         if (data.length > 0) {
             return res.cc('400', '分类名称重复')
         }

         //数据库的修改
         const [num] = await CateModel.update(req.body, {
             where: {
                 id
             }
         })
         if (num > 0) {
             res.cc(204, '修改成功')
         } else {
             res.cc(400, '修改失败')
         }
    }catch(e){
        res.cc(400,e.message)
    }
   
})







module.exports = router